package com.pu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.Page;
import com.pu.constant.MessageConstant;
import com.pu.constant.StatusConstant;
import com.pu.context.BaseContext;
import com.pu.dto.DishDTO;
import com.pu.dto.DishPageQueryDTO;
import com.pu.entity.*;
import com.pu.exception.DeletionNotAllowedException;
import com.pu.exception.SetmealEnableFailedException;
import com.pu.mapper.DishFlavorMapper;
import com.pu.mapper.DishMapper;
import com.pu.mapper.SetmealDishMapper;
import com.pu.result.PageResult;
import com.pu.service.DishFlavorService;
import com.pu.service.DishService;
import com.pu.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Author Yusc
 * @Date 2023/10/26 23:40
 * @Version
 * @Description 菜品管理
 **/
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    /**
     * @param dishDTO
     * @auther: Yusc
     * @date 2023/10/26 23:41
     * @Description 新增菜品和对应的口味
     */
    @Override
    @Transactional      //因为同时要插入两张表，需要做到要么同时成功要么同时失败
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        dish.setCreateTime(LocalDateTime.now());    //创建时间
        dish.setUpdateTime(LocalDateTime.now());    //修改时间
        dish.setCreateUser(BaseContext.getCurrentId()); //创建人id
        dish.setUpdateUser(BaseContext.getCurrentId()); //修改人id

        BeanUtils.copyProperties(dishDTO, dish);    //拷贝属性

        //向菜品表插入1条数据
        dishMapper.insert(dish);

        Long dishId = dish.getId(); // 获取菜品ID
        // 拿出口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && !flavors.isEmpty()) {    //判断员工是否传入数据
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId); // 菜品id就是插入菜品数据时的主键值
            });
            dishFlavorService.saveBatch(flavors);   // 向口味表中插入n条数据
        }
    }

    /**
     * @param dishPageQueryDTO
     * @auther: Yusc
     * @date 2023/10/27 0:49
     * @Description 菜品分页查询
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        // 1、开始分页
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        // 2、分页查询
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * @param ids
     * @auther: Yusc
     * @date 2023/10/27 11:09
     * @Description 批量删除菜品
     */
    @Override
    @Transactional //开启事务
    public void deleteBatch(List<Long> ids) {
        //1、判断当前菜品是否能够删除---是否存在起售中的菜品？？？
        for (Long id : ids) {
            Dish dish = dishMapper.selectById(id);
            if (Objects.equals(dish.getStatus(), StatusConstant.ENABLE)) {
                //当前菜品处于起售中，不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }

        //2、判断当前菜品是否能够删除---是否被套餐关联了？？？
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (setmealIds != null && !setmealIds.isEmpty()) {
            //当前菜品被套餐关联了，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //3、删除菜品表中的菜品数据
        dishMapper.deleteBatchIds(ids); //批量删除菜品

        // 4、删除菜品关联的口味数据
        dishFlavorMapper.deleteBatchDishIds(ids);

    }

    /**
     * @param id
     * @auther: Yusc
     * @date 2023/10/28 16:27
     * @Description 根据id查询菜品
     */
    @Override
    public DishVO getByIdWithFlavor(Long id) {
        // 1、根据id查询菜品数据
        Dish dish = dishMapper.selectById(id);
        // 2.1、构建查询条件
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<DishFlavor>()
                .eq(DishFlavor::getDishId, id);
        // 2.2、根据菜品id查口味数据
        List<DishFlavor> dishFlavors = dishFlavorMapper.selectList(wrapper);
        // 3、将查询到的数据封装到DishVo中
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }


    /**
     * @param dishDTO
     * @auther: Yusc
     * @date 2023/10/28 16:48
     * @Description 根据id修改菜品基本信息和对应的口味信息
     */
    @Override
    public void updateWithFlavor(DishDTO dishDTO) {
        // 1、根据id修改菜品基本信息
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);    // 属性拷贝
        dish.setUpdateTime(LocalDateTime.now());    // 设置更新时间
        dish.setUpdateUser(BaseContext.getCurrentId()); //修改人id
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<Dish>()
                .eq(Dish::getId, dish.getId());  // 构造更新条件
        dishMapper.update(dish, wrapper);

        // 2、先根据菜品id删除原有的口味信息
        LambdaQueryWrapper<DishFlavor> deleteWrapper = new LambdaQueryWrapper<DishFlavor>()
                .eq(DishFlavor::getDishId, dish.getId());  // 构造删除条件
        dishFlavorMapper.delete(deleteWrapper);

        // 3、插入传入的口味信息
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && !flavors.isEmpty()) {    //判断员工是否传入数据
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dish.getId()); // 菜品id就是插入菜品数据时的主键值
            });
            dishFlavorService.saveBatch(flavors);   // 向口味表中插入n条数据
        }

    }

    /**
     * @param categoryId
     * @auther: Yusc
     * @date 2023/10/28 17:17
     * @Description 根据分类id查询菜品
     */
    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }

    /**
     * @param status
     * @param id
     * @auther: Yusc
     * @date 2023/10/28 18:01
     * @Description 菜品的起售和停售
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        // 停售菜品时，判菜品是否在套餐中起售,有起售套餐提示"套餐内包含起售菜品，无法停售"
        if (Objects.equals(status, StatusConstant.DISABLE)) {
            // 根据菜品id查套餐
            List<Setmeal> setmeals = setmealDishMapper.getByDishId(id);
            if (setmeals != null && !setmeals.isEmpty()) {
                setmeals.forEach(setmeal -> {   // 判菜品是否在套餐中起售
                    if (StatusConstant.ENABLE.equals(setmeal.getStatus())) {
                        throw new SetmealEnableFailedException(MessageConstant.DISH_STOP_FAILED);
                    }
                });
            }

        }

        Dish dish = new Dish();
        dish.setId(id);     // 获取id
        dish.setStatus(status); //状态
        dish.setUpdateTime(LocalDateTime.now());    //更新时间
        dish.setUpdateUser(BaseContext.getCurrentId()); //更新人id

        // 更新
        lambdaUpdate().eq(Dish::getId, dish.getId())
                .update(dish);
    }

    /**
     * @param dish
     * @auther: Yusc
     * @date 2023/10/31 17:05
     * @Description 条件查询菜品和口味
     */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        // 1、根据分类id查询菜品
        List<Dish> dishList = dishMapper.list(dish);

        // 2、条件查询口味数据，并将数据封装到dishVOList中
        List<DishVO> dishVOList = new ArrayList<>();
        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d, dishVO);    // 属性拷贝

            //根据菜品id查询对应的口味
            LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<DishFlavor>()
                    .eq(DishFlavor::getDishId, d.getId());
            List<DishFlavor> flavors = dishFlavorMapper.selectList(wrapper);

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }
        return dishVOList;
    }
}
